import { useMessage } from '@/hooks/web/useMessage';
const { createMessage } = useMessage();

export const blobToObj = (data) => {
    return new Promise((resolve) => {
        if (data?.type == 'application/json') {
            const reader = new FileReader();
            reader.readAsText(data, 'utf-8');
            reader.onload = function (e) {
                try {
                    const parseObj = JSON.parse(e.target?.result as string);
                    resolve(parseObj);
                } catch (error) {
                    resolve({
                        code: -1,
                        msg: '获取失败',
                    });
                }
            };
        }
    });
};

/**
 * 下载方法
 * @param response
 */
export const downloadFile = (response) => {
    const res = response.data;
    const type = res.type;
    if (type.includes('application/json')) {
        const reader = new FileReader();
        reader.onload = (e) => {
            if (e.target?.readyState === 2) {
                const data = JSON.parse(e.target?.result as string);
                createMessage.warning(data.msg);
            }
        };
        reader.readAsText(res);
    } else {
        const disposition = response?.headers?.['content-disposition'];
        let fileName = '下载文件.zip';
        if (disposition) {
            const respcds = disposition.split(';');
            for (let i = 0; i < respcds.length; i++) {
                const header = respcds[i];
                if (header !== null && header !== '') {
                    const headerValue = header.split('=');
                    if (headerValue !== null && headerValue.length > 0) {
                        if (headerValue[0].trim().toLowerCase() === 'filename') {
                            fileName = decodeURI(headerValue[1]);
                            break;
                        }
                    }
                }
            }
        }
        //处理引号
        if (
            (fileName.startsWith("'") || fileName.startsWith('"')) &&
            (fileName.endsWith("'") || fileName.endsWith('"'))
        ) {
            fileName = fileName.substring(1, fileName.length - 1);
        }

        const blob = new Blob([res]);
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
    }
};
